<script lang="ts" setup>
import { ref } from 'vue';
import axios from 'axios';

const inputText = ref('帮我用李白的风格写一首诗');
const messages = ref([]);
const sendLoading = ref(false);
const requestAI = async () => {
  const openaiApiKey = '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';
  const apiUrl = 'https://api.openai.com/v1/completions';
  messages.value.push(`(客户爸爸: ${inputText.value})\n`);
  inputText.value = '';
  sendLoading.value = true;
  const { data } = await axios.post(
    apiUrl,
    {
      prompt: messages.value.join(),
      model: 'text-davinci-003',
      max_tokens: 2048,
      temperature: 0
    },
    {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${openaiApiKey}`
      }
    }
  );

  let resp_text: string = data.choices[0].text.trim();
  if (resp_text !== '') {
    let count = 0;
    for (let t of resp_text) {
      if (!['，',','].includes(t)) break;
      count = count + 1;
    }
    resp_text = resp_text.substring(count, resp_text.length);
    messages.value.push(resp_text);
  }
  sendLoading.value = false;
};
</script>

<template>
  <div class="p-4">
    <div class="mb-2" v-for="(message, index) in messages" :key="index">
      <p>{{ message }}</p>
    </div>
    <form class="flex w-80" @submit="requestAI">
      <el-input class="mr-2 w-full" v-model="inputText" placeholder="请输入问题" />
      <el-button size="default" type="primary" :loading="sendLoading" @click="requestAI">提交</el-button>
    </form>
  </div>
</template>

<style lang="scss" scoped></style>
